<template>
  <div>
    <el-form :inline="true" :model="user" ref="user" class="demo-form-inline">
      <el-form-item label="关键字" prop="username">
        <el-input v-model="user.username" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item label="姓别" prop="sex">
        <el-select v-model="user.sex" style="width: 100px" placeholder="请选择">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="日期范围" prop="createTime1">
        <el-date-picker
            v-model="user.createTime1"
            type="date"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-ddTHH:mm:ssZ"
            placeholder="开始日期">
        </el-date-picker>
      </el-form-item>
        __
      <el-form-item label="" prop="createTime2">
        <el-date-picker
            v-model="user.createTime2"
            type="date"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-ddTHH:mm:ssZ"
            placeholder="截止日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="onSearch">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="" icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
      </el-form-item><br />
    </el-form>
<!--    模态层-->
<!--    表单校验 :rules ref -->
<!--    表单重置 :rules ref prop 注意这三个属性放置的位置-->
    <el-dialog :title="title"  style="margin-left:300px;width: 1000px;height: 1200px;"  :visible.sync="dialogFormVisible">
      <el-form :model="newUser" :rules="rules" ref="newUser"  label-width="80px">
        <el-form-item label="用户名"  prop="username">
          <el-input style="width: 300px" v-model="newUser.username" value="" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item  label="密码" prop="password">
          <el-input style="width: 300px" v-model="newUser.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item  label="手机号" prop="phone">
          <el-input style="width: 300px" v-model="newUser.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="余额" prop="money">
          <el-input style="width: 300px"  v-model="newUser.money" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="newUser.sex">
            <el-radio label="男"  >男</el-radio>
            <el-radio label="女"  >女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
              style="width: 300px"
              v-model="newUser.createTime"
              type="date"
              format="yyyy-MM-dd HH:mm:ss"

              placeholder="请选择">
          </el-date-picker>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd('newUser')">取 消</el-button>
        <el-button type="primary" @click="addUser('newUser')">确 定</el-button>
      </div>
    </el-dialog>
<!--data就是标签自带的属性, 使用:绑定后可将表单中的值传入tableData中-->
    <el-table
        :data="tableData"
        stripe
        @selection-change= "handleSelectionChange" >
      <el-table-column
          type="selection">
      </el-table-column>
      <el-table-column
          prop="id"
          label="序号">
      </el-table-column>
      <el-table-column
          prop="username"
          label="用户名">
      </el-table-column>
      <el-table-column
          prop="password"
          label="密码">
      </el-table-column>
      <el-table-column
          prop="phone"
          label="手机号">
      </el-table-column>
      <el-table-column
          prop="money"
          label="余额">
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="注册时间">
      </el-table-column>
      <el-table-column
          prop="sex"
          label="性别"
          filter-placement="bottom-end">
<!--        插槽,scope对象能获得当前行数据-->
        <template slot-scope="scope">
          <el-tag
              :type="scope.row.sex == '男' ? 'success':'danger'"
              disable-transitions>{{scope.row.sex == '男' ? '男':'女'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="editUserById(scope.row)"

              >编辑</el-button>
          <el-button
              size="mini"
              type="danger"
              @click="delUserById(scope.row.id)"
              >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-button type="danger" icon="el-icon-delete-solid" style="margin-top: 15px" size="small" @click="batchDelUser">批量删除</el-button>
      <el-button type="primary"  icon="el-icon-circle-plus-outline" style="margin-top: 15px" size="small" @click="dialogFormVisible = true">添加</el-button>
    </div>
<!--    <div style="margin-top: 20px; display: inline-block">-->
<!--      <el-button @click="toggleSelection()">取消选择</el-button>-->
<!--    </div>-->
    <div class="pagination-block">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="user.pageNum"
          :page-sizes="[3, 4, 8,2]"
          :page-size="user.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
      <el-button type="primary" @click.prevent="toPage" icon="el-icon-s-promotion
">跳转</el-button>
    </div>
  </div>
</template>

<script>
import axios from "axios";


export default {
  name:"UserView",
  data() {
    // 校验器放在data中return前
    var validatePhone = (rule, value, callback) => {
      if (value == '') {
        callback(new Error('请输入手机号'));
      } else {
        const reg = /^\d{11}/
        if (reg.test(value)){
          callback();
        }else{
          callback(new Error('手机号需要11位'));
        }
      }
    };
    return {
      //
      tableData: [],
      multipleSelection: [],
      user:{
        username:null,
        sex:null,
        createTime1:null,
        createTime2:null,
        pageNum:1,
        pageSize:3,
      },
      newUser:{},
      total: 0,
      dialogFormVisible:false,
      formLabelWidth:100,
      title:"添加用户",
      rules:{
        username:[
          {required:true,message:'请输入用户名',trigger:"blur"},
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        password:[
          {required:true,message:'请输入密码',trigger:"blur"}
        ],
        phone:[
          { validator: validatePhone, trigger: 'blur' }
        ],
      },

    }
  },
  methods: {
    batchDelUser(){
      this.$confirm("确定删除么?",'删除用户',{
        confirmButtonText:'确定',
        cancelButtonText:'取消'
      }).then(()=>{
        axios.get("http://localhost:8082/user/batchDelUser",{
          params: {
            idList:this.multipleSelection.join(",")
          }
        }).then(res => {
          if (res.data.data>0){
            this.$message.success("删除成功")
            this.findAll()
          }
        }).catch(error => {
          console.log(error)
        })
      })
    },
    cancelAdd(formName){
      this.dialogFormVisible = false
      this.newUserReset(formName)
    },
    addUser(formName){
      this.dialogFormVisible=false
      if (this.title == "添加用户"){
        axios.post("http://localhost:8082/user/add",this.newUser)
            .then(res => {
              if (res.data.coding == "20000"){
                console.log(res)
                this.$message.success("添加成功")
                this.findAll() //重新查询
                this.newUserReset(formName) //清空表单中的数据
              }
            })
            .catch(error => {
              console.log(error)
            })
      }else{
        console.log("title",this.title)
        console.log("newUser",this.newUser)
        axios.post("http://localhost:8082/user/editV2",this.newUser)
            .then(res => {
              if (res.data.coding == "20000"){
                console.log(res)
                this.$message.success("修改成功")
                this.findAll() //重新查询
                this.newUserReset(formName) //清空表单中的数据
              }
            })
            .catch(error => {
              console.log(error)
            })
      }

    },
    newUserReset(formName){
      this.$refs[formName].resetFields();
    },
    editUserById(row){
      this.title='更新用户'
      this.dialogFormVisible=true
      this.newUser=row
    },
    delUserById(id){
      axios.get("http://localhost:8082/user/del",{
        params:{
          // 后端方法中的参数 ： 表单数据（或者说是data中的）
          id:id
        }
      }).then(res => {
        if (res.data.data == 1){
          this.$message.success("操作成功")
          this.findAll()
        }
        // console.log(res)
      }).catch(error => {
        console.log(error)
      })
    },
    onSearch() {
      axios
          .get("http://localhost:8082/user/list/page2",{
            params:this.user
          })
          .then(res => {
            this.tableData = res.data.data.list
            this.total = res.data.data.total
          })
          .catch(error => {
            console.log("error"+error)
          })
      // 查询结束后将tableData中的数据清空
      this.tableData=[]
    },

    findAll(){
      axios
          .get("http://localhost:8082/user/list/page",{
            params:{
              pageNum : this.user.pageNum,
              pageSize: this.user.pageSize,
            }
          })
          .then(res => {
            this.tableData = res.data.data.list,
            this.total = res.data.data.total
          })
          .catch(error => {
            console.log(error)
          })
    },
    handleSelectionChange(val) {
      // this.multipleSelection = [];
      // for (const valKey in val) {
      //   this.multipleSelection.push(this.tableData[valKey].id)
      // }
      // 使用数组的map函数优化取值
      this.multipleSelection = val.map(user => user.id)
      console.log(this.multipleSelection)
    },
    handleSizeChange(val) {
      this.user.pageSize = val
      this.findAll()
    },
    handleCurrentChange(val) {
      this.user.pageNum = val
      this.findAll()
    },
    toPage(){
      this.findAll()
    },
    resetForm() {
        this.user.username=null,
        this.user.sex=null,
        this.user.createTime1=null,
        this.user.createTime2=null
    }
  },
  created() {
    this.findAll()
  }
}
</script>

<style scoped>
.el-radio__original {
  aria-hidden: false !important;
}

.pagination-block {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
}

.pagination-block .el-pagination {
  margin-right: 10px;
}

.pagination-block .el-button {
  height: 28px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
